//出入库申请同步NC 回写 
global class InstrumentDeliverySyncUtil {
    public InstrumentDeliverySyncUtil(){}


    @RemoteAction
    public static String changeRecordType(String mainId,String type ){

        try {
           
            Id rtId =  Utils.getRecordTypeIdByDevNameAndObjName(type,'InstrumentDeliveryApplication__c') ;

            update new InstrumentDeliveryApplication__c(Id=mainId,RecordTypeId = rtId);
        }
        catch (Exception e) {
            
            return '理改失败:'+e.getMessage(); 
        }
        

        return 'OK';
    }
    @RemoteAction 
    public static Map<String,String> getDetails(String mainId ){

        Map<String,String> resMap = new Map<String,String>();
        
            System.debug('InstrumentDeliverySyncUtil==>'+ mainId );

            InstrumentDeliveryApplication__c ida = [select Id from  InstrumentDeliveryApplication__c where Id=:mainId ];

            Set<String> pks = new Set<String>();
           /* for (InstrumentDeliverynDetails__c idd  : [select Id,DeliveryInstrument__r.Product__r.pk_invbasdoc__c 

                from InstrumentDeliverynDetails__c where  ReturnToMainTable__c =:mainId 

                and DeliveryInstrument__r.Product__r.InstrumentType__c = '非维保仪器'] ) {
                    
                    pks.add(idd.DeliveryInstrument__r.Product__r.pk_invbasdoc__c );

            }*/
            List<Map<String,String>>comfirmList = new List<Map<String,String>>();
            for (NCOutsourcingProducts__c np: [select Id ,Name ,Number__c,InstrumentDeliveryDetails__r.Number__c, NCProducts__r.pk_invbasdoc__c from NCOutsourcingProducts__c where InstrumentDeliveryDetails__r.ReturnToMainTable__c =: ida.Id ] ) {
                pks.add(np.Id);
                Map<String,String> d = new Map<String,String>();
                d.put('Name',np.Name);
                d.put('SFNum', String.valueOf(np.Number__c * np.InstrumentDeliveryDetails__r.Number__c ));
                d.put('NCNum', '0');
                comfirmList.add(d);
            }
            resMap.put('mainId', ida.Id);
            resMap.put('pks', EncodingUtil.urlEncode(String.join(new List<String>(pks), '\',\''), 'utf-8') );
            resMap.put('details', EncodingUtil.urlEncode(JSON.serialize(comfirmList), 'utf-8'));
           
        return resMap;


    }
    @RemoteAction 
    public  static String   backWriteFromNc(String mainId , List<Map<String,String>> data ){


        try {


            InstrumentDeliveryApplication__c ida = [select Id,ReceivingCustomer__c,ReceivingDepartment__c ,
            RecordType.DeveloperName ,WarehouseReceiptTime__c 
             from InstrumentDeliveryApplication__c where Id =: mainId];
             if(ida.WarehouseReceiptTime__c != null ) return '已确认过出库无须重复确认!';
            
             Map<String,Decimal> allDetails = new Map<String,Decimal>();
             Map<String,String> detailMap = new Map<String,String>();
             //DeliveryInstrument__r.Product__r.InstrumentType__c ,

             Map<Id,NCOutsourcingProducts__c> detailInfoMap = new Map<Id,NCOutsourcingProducts__c>();
             for (InstrumentDeliverynDetails__c idd :[select Id,Number__c,
                (select Id ,Name ,Number__c,NCProducts__r.Category0__c,NCProducts__r.InstrumentType__c,OrderMethod__c from InstrumentDeliveryDetails__r   ) 
                from  InstrumentDeliverynDetails__c where ReturnToMainTable__c =:mainId  ] ) {

                
                 /*if(idd.DeliveryInstrument__r.Product__r.InstrumentType__c != null && idd.DeliveryInstrument__r.Product__r.InstrumentType__c == '非维保仪器'){
                    

                    allDetails.put(idd.Id, idd.Number__c);

                 }else{

                    for (NCOutsourcingProducts__c np  :idd.InstrumentDeliveryDetails__r  ) {

                        if(np.NCProducts__r.Category0__c == '仪器')allDetails.put(np.Id,idd.Number__c * np.Number__c);
                        detailMap.put(np.Id ,idd.Id);

                    }


                }*/

                for (NCOutsourcingProducts__c np  :idd.InstrumentDeliveryDetails__r  ) {

                        if((np.NCProducts__r.Category0__c == '仪器' || np.NCProducts__r.Category0__c =='辅助器械' || np.NCProducts__r.Category0__c =='开栓') && np.OrderMethod__c != '客户自备' )allDetails.put(np.Id,idd.Number__c * np.Number__c);
                        detailMap.put(np.Id ,idd.Id);
                        detailInfoMap.put(np.Id, np);


                    }
             }
            

            //List<InstrumentDeliverynDetails__c> idList =new List<InstrumentDeliverynDetails__c>();

            
            Map<String,Set<String>> pMap = new Map<String, Set<String>>();
            Map<String,String> installDateMap = new Map<String ,String>();
            System.debug(allDetails);

            Map<String,InstrumentDeliverynDetails__c> idMap = new Map<String,InstrumentDeliverynDetails__c>();

            Map<Id,NCOutsourcingProducts__c> npMap = new Map<Id,NCOutsourcingProducts__c>();
            System.debug(data);
            System.debug(detailMap);
            Map<String,Decimal> numMap = new Map<String,Decimal>();
            //机身号
            Map<String,Set<String>> alleNos  = new Map<String,Set<String>>();

            for(Map<String,String> m :data){

                System.debug(m);
                Decimal d =  m.get('num') == null ? 0 :Decimal.valueOf(String.valueOf(m.get('num')).trim()) ;
                
                String detailId = m.get('subId');//npId 
                numMap.put(detailId, numMap.containsKey(detailId)? d+numMap.get(detailId) : d );

                //if(Id.valueOf(detailId).getSObjectType() == NCOutsourcingProducts__c.SObjecttype ){

                    
                    String mId = detailMap.get(detailId);
                    InstrumentDeliverynDetails__c idd = idMap.containsKey(mId) ? idMap.get(mId ): new InstrumentDeliverynDetails__c();
                    idd.Id =mId ;


                    System.debug(allDetails.containsKey(detailId) +' '+ m.get('eno') );

                    if( allDetails.containsKey(detailId) ) idd.OutdoorNo__c = m.get('outno');
                    //如果不是仪器 则不组装机身号
                    String eno =  allDetails.containsKey(detailId) ? (m.get('eno') == null || m.get('eno') == 'null' ? '' : m.get('eno')) : ''  ;

                    String enos = String.isBlank(idd.FuselageNumber__c) ?  eno  : idd.FuselageNumber__c +  (eno ==  '' ? '' : '*'+eno)   ; 
                    //idd.FuselageNumber__c = eno.length() > 255 ? eno.substring(0, 254) : eno;
                    idd.FuselageNumber__c = enos == null ? null : ( enos.length() > 255 ? enos.substring(0, 254) : enos );

                    idMap.put(idd.Id , idd);

                    Set<String> eSets = alleNos.containsKey(idd.Id ) ? alleNos.get(idd.Id ) :  new Set<String>();
                    eSets.add(eno);
                    alleNos.put(idd.Id , eSets);




                    NCOutsourcingProducts__c np = npMap.containsKey(detailId) ? npMap.get(detailId) : new NCOutsourcingProducts__c();
                    np.Id = detailId;

                    np.OutgoingSingleNumber__c = m.get('outno');
                    
                    np.SerialNumber__c = np.SerialNumber__c  == null ?   eno :  eno == null ? np.SerialNumber__c :  np.SerialNumber__c +'*'+ eno ;
                    npMap.put(detailId, np);

                    //处理小型仪器
                    if(m.get('signdate') != null )installDateMap.put(idd.Id ,m.get('signdate') );
                    Set<String> enoset  = pMap.containsKey(idd.Id) ? pMap.get(idd.Id): new Set<String>();
                    if(eno.length() > 0  )enoset.add(eno);
                    pMap.put(idd.Id , enoset);


                    
                    


              /*  }else{//小型仪器

                    String mId = m.get('subId');
                    InstrumentDeliverynDetails__c idd =  idMap.containsKey(mId) ? idMap.get(mId ): new InstrumentDeliverynDetails__c();
                    idd.Id = mId;
                    String eno =  m.get('eno') == null || m.get('eno') == 'null' ? '' : m.get('eno')  ;
                    
                    idd.OutdoorNo__c =  m.get('outno') ;

                    String enos = idd.FuselageNumber__c == null ?  eno  : idd.FuselageNumber__c +  (eno ==  '' ? '' : '*'+eno)   ; 

                    idd.FuselageNumber__c = enos == null ? null : ( enos.length() > 255 ? enos.substring(0, 254) : enos );

                    idMap.put(idd.Id , idd);

                    Set<String> enoset  = pMap.containsKey(idd.Id) ? pMap.get(idd.Id): new Set<String>();

                    if(eno.length() > 0  )enoset.add(eno);

                    pMap.put(idd.Id , enoset);

                    if(m.get('signdate') != null )installDateMap.put(idd.Id ,m.get('signdate') );


                }*/
                System.debug(idMap);
                

            }

            List<Map<String,String>>comfirmList = new List<Map<String,String>>();
            for (String detailId :allDetails.keySet()  ) {

                Map<String,String> d = new Map<String,String>();
                d.put('Name',detailInfoMap.containsKey(detailId) ? detailInfoMap.get(detailId).Name : detailId );
                d.put('SFNum', String.valueOf(allDetails.get(detailId)));
                d.put('NCNum', String.valueOf(numMap.get(detailId)));
                comfirmList.add(d);
                if(numMap.get(detailId) ==  allDetails.get(detailId))allDetails.remove(detailId);
            }



            if(!allDetails.isEmpty()) return EncodingUtil.urlEncode(JSON.serialize(comfirmList), 'utf-8');


            //找到小型仪器
            List<InstrumentDeliverynDetails__c> smalls = [select Id ,DeliveryInstrument__r.Product__c ,DeliveryInstrument__r.EnterWay__c   
            from InstrumentDeliverynDetails__c  where Id in: pMap.keySet() and DeliveryInstrument__r.Product__r.InstrumentType__c = '非维保仪器' ];
            

            Map<String,Equipment__c> eqMap  = new Map<String,Equipment__c>();

            Set<String> enoset = new Set<String>();
            for (InstrumentDeliverynDetails__c idd  : smalls) {

                if(!pMap.containsKey(idd.Id ))continue;//小型仪器如果没有机身号就不生成资产

                for (String eno  : pMap.get(idd.Id )) {

                    Equipment__c eq = new Equipment__c();

                    eq.Product__c = idd.DeliveryInstrument__r.Product__c ;
                    eq.Account__c = ida.ReceivingCustomer__c  ;
                    eq.IMEINumber__c = eno;
                    eq.OpponentDept__c = ida.ReceivingDepartment__c ; 
                    eq.OpponentStatus__c = '安装未使用';
                    eq.WhetherStandalone__c = '是';
                    eq.EnterWay__c = idd.DeliveryInstrument__r.EnterWay__c ;
                    eq.InstrumentDeliverynDetails__c = idd.Id;
                    eq.FromWorkOrder__c  = true;
                    if(installDateMap.containsKey(idd.Id ))eq.EndDate__c = Date.valueOf(installDateMap.get(idd.Id).trim());
                    eqMap.put(ida.ReceivingCustomer__c+'-'+eq.Product__c+'-'+eno,eq);
                    enoset.add(eno );

                }
                
            }

            //验证是否存在 如果 已经存在,不重复生成
            for ( Equipment__c eq : [ select  Id ,Account__c,IMEINumber__c ,Product__c from Equipment__c 

                where Account__c =:ida.ReceivingCustomer__c and IMEINumber__c in:enoset ] ) {
                System.debug('eq');
                if(eqMap.containsKey(eq.Account__c+'-'+eq.Product__c+'-'+eq.IMEINumber__c))eqMap.remove(eq.Account__c+'-'+eq.Product__c+'-'+eq.IMEINumber__c);
                System.debug(eqMap);
            }

            Map<Id,Integer> inMap = new Map<Id,Integer>();
            List<InstallationApply__c>   inL = [select Id ,FuselageNumber__c ,InstallInstruments__c from InstallationApply__c where InstallInstruments__c in:alleNos.keySet() Order by InstallInstruments__c,Id ];
            for( InstallationApply__c ia : inL  ){

                Integer i = inMap.containsKey(ia.InstallInstruments__c ) ? inMap.get(ia.InstallInstruments__c)  +1 : 0;
                inMap.put(ia.InstallInstruments__c,i );

                if(ia.FuselageNumber__c != null )continue;
                List<String> enosL = new  List<String> (alleNos.get(ia.InstallInstruments__c));
                ia.FuselageNumber__c = enosL.size() > i ? enosL.get(i) : null;



            }
            SavePoint sp = Database.setSavepoint();
            try {
                ida.WarehouseReceiptTime__c = System.today();
                update ida;
                if(inL.size() > 0 ) update inL;
               if(!eqMap.isEmpty()) insert eqMap.values();

               if(idMap.keySet().size() > 0 ) update idMap.values();
               if(npMap.isEmpty() ) update npMap.values();
               return '确认成功!';
            }
            catch (Exception e) {
                Database.rollback(sp);
                return '确认失败:'+e.getMessage()+e.getStackTraceString();
            }
            
            
        }catch (Exception e) {
              return '确认失败:'+e.getMessage()+e.getStackTraceString();


        }
        
        

    }
    public static String  getCompanyCode( String companystr ){

        Map<String,String>  comMap = new Map<String,String>();
        for(String ss : Label.ShortCompanyName.split(',')){
            String[] s = ss.split('-');
            if(s.size() > 1){
                comMap.put(s[1], s[0]);
            }

        }
        for(String k : comMap.keySet()){

            if(companystr.contains(k))return comMap.get(k);
        }
        return null;

    }

    public static String getUid(String uid  ){

        if(uid != null ){
            while(uid.length() < 6){
                uid= '0'+uid;
            }
        }
        return uid;
    }
    Webservice  static  String  SyncToNC(String iid ,Boolean isQixie ){

        if(iid == null )return '参数异常!';
        //分为两种情况 : 销售  投放

        //1.判断仪器数量是否小于等于可发货数量
        //2.判断字段是否填写
        //3.组装数据
        //4.同步NC
        //5.数量反写到合同 发货申请反写已同步标记 锁定记录

        //投放
        return sync(iid,isQixie );


        


    }
    public   static String sync(String iid,Boolean isQixie ){
        InstrumentDeliveryApplication__c ida = [select GroupAllocation__c,Id,Owner.Name,OwnerId,RecordType.DeveloperName,ResultMsg__c,Status__c,
            Remark__c,ReceiverTelephone__c,FollowupProcessing__c,DocumentTypes__c,InvoicingCustomers__r.AccountNumber,
             InventoryStatus__c,PhysicalDelivery__c,InvoicingCustomers__r.Name ,NC__c,ReceivingAddress__c,ReceivingCustomer__c,ReceivingCustomer__r.AccountNumber  
             from InstrumentDeliveryApplication__c where Id =: iid];
             System.debug(ida.RecordType.DeveloperName);


             if(ida.InventoryStatus__c == null )return '出库方式不能为空';
             if(ida.GroupAllocation__c != null && ida.GroupAllocation__c == 'Y' && !(ida.Status__c == '审批中' || ida.Status__c == '已批准' )) return '调拨出库的发货申请须先提起审批!';

             if(ida.RecordType.DeveloperName == 'SalesOutlet'){
                
                return syncSaleOutApplication(ida);

             }else{
                
                return syncOutApplication(ida,isQixie);
             }


    }
    //销售出库
    public static String syncSaleOutApplication(InstrumentDeliveryApplication__c ida){

        /*InstrumentDeliveryApplication__c ida = [select Id,Owner.Name,OwnerId,
            Remark__c,ReceiverTelephone__c,FollowupProcessing__c,DocumentTypes__c,InvoicingCustomers__r.AccountNumber,
             InventoryStatus__c,PhysicalDelivery__c,InvoicingCustomers__r.Name ,NC__c,ReceivingAddress__c,ReceivingCustomer__c,ReceivingCustomer__r.AccountNumber  
             from InstrumentDeliveryApplication__c where Id =: iid];*/
             //if(ida.NC__c == true) return '已同步NC请不要重复同步!';
              //同步操作人
             User u = [select Id, EmployeeNumber ,Name from User where Id =:UserInfo.getUserId()];
             String operator = getUid(u.EmployeeNumber);
             User saler = [select Id,Manager.Name  from User where Id =:ida.OwnerId ];
             if(ida.InvoicingCustomers__r.AccountNumber == null ) return '请维护'+ida.InvoicingCustomers__r.Name +' 的客户编码!';
             if(operator == null ) return '请联系管理员维护工号!';
            // Map<String,String> invsMap = ImportObject.getPicklistValues('InstrumentDeliveryApplication__c', 'InventoryStatus__c', true);
            // String corpcode = getCompanyCode(invsMap.get(ida.InventoryStatus__c));
            // if(corpcode == null )return '请联系管理员维护公司简称合同Corpcode__c!';
              Map<String,String >companyMap = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
             String corpcode =companyMap.get(ida.InventoryStatus__c);
              if(corpcode == null )return '请联系管理员维护公司简称合同Corpcode__c!';

             Map<String,String> comcodeMap = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', true);
             Map<String,String> vsalestrucodeMap = ImportObject.getPicklistValues('Contract__c', 'Vsalestrucode__c', false);
        
             String vsalestrucode = vsalestrucodeMap.get(comcodeMap.get(corpcode));
             if(vsalestrucode == null )return '请联系管理员维护销售组织编码!';
            // Set<Id> dset = new Set<Id>();
            List<NCOutsourcingProducts__c> npList  = [select Id ,InstrumentDeliveryDetails__r.Number__c ,
                InstrumentDeliveryDetails__r.Name,ContractProduct__r.ApplyQuantity__c,IsSycToNc__c,

                InstrumentDeliveryDetails__c,NCProducts__r.Name,
                NCProducts__c, NCProducts__r.NCCode__c,Number__c,UnitPrice__c,OrderMethod__c,IsStandard__c,
                NCProducts__r.Category0__c , ContractProduct__c,ContractProduct__r.DeliveryQuantity__c 

                from NCOutsourcingProducts__c where InstrumentDeliveryDetails__r.ReturnToMainTable__c =: ida.Id ];// and NCProducts__r.InstrumentType__c != '非维保仪器'

                List<ContractWebService.ConProductArgs> cpList = new List<ContractWebService.ConProductArgs>();


                //查找明细
                Map<String,String> detailMap = new Map<String,String>();
            for(NCOutsourcingProducts__c np: npList ){

                //dset.add(np.InstrumentDeliveryDetails__c);
                if(np.OrderMethod__c == '客户自备' || np.OrderMethod__c == '不需订购')continue;
                if(np.InstrumentDeliveryDetails__r.Number__c == null || np.InstrumentDeliveryDetails__r.Number__c == 0   ) return np.InstrumentDeliveryDetails__r.Name + ' : 请明确仪器数量!';
                
                if(np.Number__c ==  null || np.Number__c == 0 )  return np.NCProducts__r.Name + ' :请明确仪器数量!';

                if(np.NCProducts__r.NCCode__c  == null ) return np.NCProducts__r.Name + ' :请明确发货明细对应的NC产品(确保产品有存货编码)!' ;
                if(np.UnitPrice__c  == null ) return np.NCProducts__r.Name + ' :请明确发货明细价格!' ;

                Decimal num = np.InstrumentDeliveryDetails__r.Number__c * np.Number__c;

                //if(np.ContractProduct__c != null && np.ContractProduct__r.DeliveryQuantity__c <  num ) return np.NCProducts__r.Name + ' : 发货仪器超过合同仪器可申请发货数量,不能发货!';
                if(np.IsSycToNc__c == true) continue;
                detailMap.put(np.Id ,np.InstrumentDeliveryDetails__c);
                ContractWebService.ConProductArgs cp = new ContractWebService.ConProductArgs();
                cp.corpcode = corpcode;
                cp.custcode = ida.InvoicingCustomers__r.AccountNumber;
                cp.vsalestrucode = vsalestrucode;
                cp.created_by  = u.Name;
                cp.sub_corp_manager = saler.Manager.Name;
                //cp.csourcecode = '';
                cp.ts  = System.now().format('yyyy-MM-dd HH:mm:ss');
                cp.csalequotationid = ida.Id;
                cp.csalequotation_bid = np.Id;
                
                  cp.cemployeecode = ida.Owner.Name; //所有者
                cp.invcode = np.NCProducts__r.NCCode__c; //产品的NCCode__c
                cp.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期

                 cp.noriginalcurtaxprice = String.valueof(np.UnitPrice__c); 
                
               //SalesPrice__c
                cp.nitemdiscountrate = '100';//默认100
                cp.nnumber = String.valueof(num);
                cp.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cp.quotetype = '1'; //报价类型   1=报价  2=调价
               
                cp.currtypename = '人民币';
               // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                cpList.add(cp);


            }
          /*  for (InstrumentDeliverynDetails__c idd : [select Id,DeliveryInstrument__r.Product__r.Name ,DeliveryInstrument__r.Product__r.NCCode__c,Number__c,
                DeliveryInstrument__r.SalesPrice__c ,IsSycToNc__c 
                from InstrumentDeliverynDetails__c where ReturnToMainTable__c =: ida.Id and  DeliveryInstrument__r.Product__r.InstrumentType__c = '非维保仪器']) {
                //if(dset.contains(idd.Id))continue;
                if(idd.Number__c ==  null || idd.Number__c == 0 )  return idd.DeliveryInstrument__r.Product__r.Name + ' :请明确仪器数量!';
                if(idd.IsSycToNc__c == true) continue;
                ContractWebService.ConProductArgs cp = new ContractWebService.ConProductArgs();
                cp.corpcode = corpcode;
                cp.custcode = ida.InvoicingCustomers__r.AccountNumber;
                cp.vsalestrucode = vsalestrucode;
                cp.created_by  = u.Name;
                cp.sub_corp_manager = saler.Manager.Name;
                //cp.csourcecode = '';
                cp.ts  = System.now().format('yyyy-MM-dd HH:mm:ss');
                cp.csalequotationid = ida.Id;
                cp.csalequotation_bid = idd.Id;
                
                 cp.cemployeecode = ida.Owner.Name; //所有者
                cp.invcode = idd.DeliveryInstrument__r.Product__r.NCCode__c; //产品的NCCode__c
                cp.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期

                 cp.noriginalcurtaxprice = String.valueof(idd.DeliveryInstrument__r.SalesPrice__c); 
                
               //SalesPrice__c
                cp.nitemdiscountrate = '100';//默认100
                cp.nnumber = String.valueof(idd.Number__c);
                cp.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cp.quotetype = '1'; //报价类型   1=报价  2=调价
               
                cp.currtypename = '人民币';
                cpList.add(cp);

            }
*/


            if(cpList.isEmpty()) return '同步成功!';
            String msg = '';
            System.debug('InstrumentDeliverySyncUtil==>'+JSON.serialize(detailMap));


          Map<String ,List<ContractWebService.ConProductArgs>>temp = new Map<String ,List<ContractWebService.ConProductArgs>>();
          temp.put('data',cpList);

          String body = JSON.serialize(temp);
            System.debug(body);
            HttpRequest req = new HttpRequest();
            req.setBody(body);
            //return body;
            req.setMethod('POST');
            req.setHeader('Content-Type','text/plain');
            // 接口写在自定义标签的quoteUrl里面
            req.setEndpoint(System.Label.quoteUrl);

            System.debug('+++'+ body);
            
            HttpResponse res = Utils.postRequest(req, 1);
             System.debug('+++'+res.getBody());
         
            if (res.getStatusCode() == 200) {
                Map<String,Object> r = new Map<String,Object>();
                //如果是测试
                if(Test.isRunningTest()){

                    Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"操作成功！\",\"result\":1,\"data\":{\"ts\":\"2018-01-04 16:24:18\"}}');
                    r =  resBody;
                }else{
                     r  = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
   
                }
               // return res.getBody();
                 if(r.get('code') == 0 || r.get('code') == '0'){
                  Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                
                    msg = '系统提示:';

                   msg +=  rs.get('result') == 0 ? '同步失败:' +(String) rs.get('result_msg')  :'同步成功';
                   if (rs.get('result') == 1 ) {

                        //成功

                        List<SObject> tmp = new List<SObject>();
                        List<SObject> tmp1 = new List<SObject>();
                        Set<String> idset = new Set<String>();
                        for(ContractWebService.ConProductArgs  ob : cpList){
                             if(idset.contains(ob.csalequotation_bid))continue;
                            SObject sob =Id.valueOf(ob.csalequotation_bid ).getSobjectType().newSObject();
                            sob.put('Id', ob.csalequotation_bid);
                            sob.put('IsSycToNc__c', true);
                           idset.add(ob.csalequotation_bid);
                            tmp.add(sob);
                            if(detailMap.containsKey(ob.csalequotation_bid)){
                                if(idset.contains(detailMap.get(ob.csalequotation_bid)))continue;
                                SObject som =Id.valueOf(detailMap.get(ob.csalequotation_bid) ).getSobjectType().newSObject();
                                som.put('Id', detailMap.get(ob.csalequotation_bid) );
                                som.put('IsSycToNc__c', true);
                                tmp1.add(som);
                                idset.add(detailMap.get(ob.csalequotation_bid) );
                            }
                        }
                        if(tmp1.size() > 0 ) update tmp1;
                        if(tmp.size() > 0 ) update tmp;
                        

                        ida.NC__c = true;
                        ida.ResultMsg__c = String.valueOf(rs.get('data'));
                        ida.SynchronizedNCTime__c = System.today();


                        try{
                            update ida;
                        }catch(Exception e){
                            return '同步成功,保存数据失败!'+e.getMessage()+e.getStackTraceString();
                        }
                        
                        try{
                            Approval.lock(ida,false); 
                        }catch(Exception e){}
                       
                        msg = '同步成功!';

                     
                    }
                     
                    return msg;
                 }else{
                    return '系统提示:' + (String)r.get('msg') ;
                 }

                   
            } else {
                return '系统错误:'+res.toString()+',请联系系统管理员!';
            }






        /*


     global String corpcode;  //报价上新增字段 公司编码 报价.corpcode__c
        global String custcode;  //客户的NCAccountNumber__c
        global String vsalestrucode;  //报价上新增字段 销售组织编码 报价.vsalestrucode__c
        global String created_by;  //报价的创建人名字
        global String sub_corp_manager;  //报价的销售中心总监名字
        global String csourcecode;  //报价的QuoteNumber
        global String ts;  //报价的lastmodifieddate
        global String csalequotationid;  //报价的id
        global String csalequotation_bid;  //报价产品的id
        global String cemployeecode;  //报价所有者
        global String invcode;  //报价产品.产品的NCCode__c
        global String noriginalcurtaxprice;  //报价产品的SalesPrice__c
        global String nitemdiscountrate;  //报价产品的DiscountRate__c
        global String nnumber;  //报价产品的Quantity__c
        global String opertype; //操作类型   1=新增  2=修改  3=删除
        global String quotetype; //报价类型   1=报价  2=调价
        global String adjustid; //调价的id
        global String adjust_pid; //调价产品的id
        global String addCustomer; //客户终端类型
        global String currtypename ; //币种
        global String dreceiptdate;//报价日期
        */
    }
     

    //投放出库 按产品的批准文号进行分单 : 存在批准文号的 为器械 不存在的为非器械
    public static String syncOutApplication(InstrumentDeliveryApplication__c ida ,Boolean isQixie){
            //器械
            List<OutdoorBean> outdoorList = new List<OutdoorBean>();
            //非器械
            //List<OutdoorBean> nonEquipOutdoorList = new List<OutdoorBean>();
          Map<String,String> detailMap = new Map<String,String>();
        try{

            /*InstrumentDeliveryApplication__c ida = [select Id,Owner.Name,
            Remark__c,ReceiverTelephone__c,FollowupProcessing__c,DocumentTypes__c,InvoicingCustomers__r.AccountNumber,
             InventoryStatus__c,PhysicalDelivery__c,NC__c,ReceivingAddress__c,ReceivingCustomer__c,ReceivingCustomer__r.AccountNumber 
             from InstrumentDeliveryApplication__c where Id =: iid];*/

             //if(ida.NC__c == true)return '已同步NC请不要重复同步!';

             //同步操作人
             User u = [select Id, ExuserCode__c from User where Id =:UserInfo.getUserId()];
             String operator = u.ExuserCode__c;

             if(operator == null ) return '请联系管理员维护工号!';
             if(ida.InventoryStatus__c == null ) return '请维护发货申请的出库方式';
             // Map<String,String> invsMap = ImportObject.getPicklistValues('InstrumentDeliveryApplication__c', 'InventoryStatus__c', true);
             
             Map<String,String >companyMap = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
             String corpcode =companyMap.get(ida.InventoryStatus__c);
             if(corpcode == null )return '请联系管理员维护公司简称合同Corpcode__c!';

            String npsql = 'select Id ,InstrumentDeliveryDetails__r.Number__c , '+
                'InstrumentDeliveryDetails__r.Name,NCProducts__r.Name , '+
                'InstrumentDeliveryDetails__c,NCProducts__r.NCvpzwh__c , IsSycToNc__c, '+

                'NCProducts__c, NCProducts__r.NCCode__c,Number__c,UnitPrice__c,OrderMethod__c,IsStandard__c, '+
                'NCProducts__r.Category0__c , ContractProduct__c,ContractProduct__r.DeliveryQuantity__c ,Remarks__c '+

                'from NCOutsourcingProducts__c where InstrumentDeliveryDetails__r.ReturnToMainTable__c =\''+ida.Id +'\'   ';//and  NCProducts__r.InstrumentType__c  != \'非维保仪器\'
            
                npsql +=  isQixie ? ' and  NCProducts__r.NCvpzwh__c != null ' : ' and  NCProducts__r.NCvpzwh__c = null ' ;
            Decimal total = 0;

           /* String sql = 'select Id,DeliveryInstrument__r.Product__r.Name ,DeliveryInstrument__r.Product__r.NCvpzwh__c , '+
                'DeliveryInstrument__r.Product__r.NCCode__c,Number__c ,IsSycToNc__c '+
                'from InstrumentDeliverynDetails__c where ReturnToMainTable__c =\''+ida.Id +'\' and  DeliveryInstrument__r.Product__r.InstrumentType__c = \'非维保仪器\'  ';
                sql +=  isQixie ? ' and  DeliveryInstrument__r.Product__r.NCvpzwh__c != null ' : ' and  DeliveryInstrument__r.Product__r.NCvpzwh__c = null ' ;
            
            for (InstrumentDeliverynDetails__c idd : Database.query(sql)) {
            
                if(idd.Number__c ==  null || idd.Number__c == 0 )  return idd.DeliveryInstrument__r.Product__r.Name + ' :请明确仪器数量!';
                total += idd.Number__c;
                if(idd.IsSycToNc__c == true )continue;
                outdoorList.add(new OutdoorBean(idd,ida,corpcode,operator ));
                //if(idd.DeliveryInstrument__r.Product__r.NCvpzwh__c != null   )outdoorList.add(new OutdoorBean(idd,ida,corpcode,operator ));
                //if(idd.DeliveryInstrument__r.Product__r.NCvpzwh__c == null   )nonEquipOutdoorList.add(new OutdoorBean(idd,ida,corpcode,operator ));

            }*/

            //查找明细
           
            for(NCOutsourcingProducts__c np: Database.query(npsql) ){

                if(np.OrderMethod__c == '客户自备' || np.OrderMethod__c == '不需订购')continue;

                if(np.InstrumentDeliveryDetails__r.Number__c == null || np.InstrumentDeliveryDetails__r.Number__c == 0   ) return np.InstrumentDeliveryDetails__r.Name + ' : 请明确仪器数量!';
                
                if(np.Number__c ==  null || np.Number__c == 0 )  return np.NCProducts__r.Name + ' :请明确仪器数量!';

                if(np.NCProducts__r.NCCode__c  == null ) return np.NCProducts__r.Name + ' :请明确发货明细对应的NC产品(确保产品有存货编码)!' ;

                Decimal num = np.InstrumentDeliveryDetails__r.Number__c * np.Number__c;
                total += num ;
                if(np.IsSycToNc__c == true )continue;
                detailMap.put(np.Id , np.InstrumentDeliveryDetails__c);

                //if(np.ContractProduct__c != null && np.ContractProduct__r.DeliveryQuantity__c <  num ) return np.NCProducts__r.Name + ' : 发货仪器('+num+')超过合同仪器已申请发货数量('+ np.ContractProduct__r.DeliveryQuantity__c+'),不能发货!';

                outdoorList.add(new OutdoorBean(np,ida,corpcode,operator ));

            
            }
            for (OutdoorBean ob  : OutdoorList) {

                ob.totalnum = String.valueOf(total);
            }

        }catch(Exception e ){

            return '同步失败:'+e.getMessage()+e.getStackTraceString();
        }

            String msg = '';
            Map<String,String> returnMap = new Map<String,String>();
            returnMap.put('code', '0');

            if(outdoorList.isEmpty())return 'ok';

            returnMap = syncOutdoor(outdoorList);
            msg = returnMap.get('code') == '0' ? 'ok' : returnMap.get('msg') ;
            System.debug('InstrumentDelieverySyncUtil==>'+ msg );

            if(msg != 'ok') return msg ;

            List<SObject> tmp = new List<SObject>();
            List<SObject> tmp1 = new List<SObject>();
            Set<String> idset = new Set<String>();


            for(OutdoorBean ob : outdoorList){
                if(idset.contains(ob.sflistid))continue;
                SObject sob =Id.valueOf(ob.sflistid ).getSobjectType().newSObject();
                sob.put('Id', ob.sflistid);
                sob.put('IsSycToNc__c', true);
                idset.add(ob.sflistid);
                tmp.add(sob);
                 if(detailMap.containsKey(ob.sflistid)){
                    if(idset.contains(detailMap.get(ob.sflistid)))continue;
                         SObject som =Id.valueOf(detailMap.get(ob.sflistid) ).getSobjectType().newSObject();
                        som.put('Id', detailMap.get(ob.sflistid) );
                        som.put('IsSycToNc__c', true);
                        idset.add(detailMap.get(ob.sflistid));
                        tmp1.add(som);
                    }
            }
            if(tmp1.size() > 0 ) update tmp1;
            if(tmp.size() > 0 ) update tmp;
           

                String resmsg = ida.NC__c == true ? (ida.ResultMsg__c == null ? '' :ida.ResultMsg__c) +  returnMap.get('msg') : returnMap.get('msg') ;
                
                ida.ResultMsg__c = resmsg == null ? null : resmsg.length() > 255 ? resmsg.substring(0, 254) : resmsg ;
                ida.NC__c = true;
                ida.SynchronizedNCTime__c = System.today();


                try{
                    update ida;
                }catch(Exception e){
                    return '同步成功,保存数据失败!'+e.getMessage()+e.getStackTraceString();
                }

                try{
                    Approval.lock(ida,false); 
                }catch(Exception e){}
            return msg; 
            


    }

    /**
        仪器发货推送请购单
    */
     WebService static String postRequireBuy(Id id) {
       
        List<InstrumentDeliveryApplication__c> eprpList = [select Id,Name,IsSycNCBuy__c,ResultMsg3__c , InventoryStatus__c,Remark__c,DemandWarehouse__c from InstrumentDeliveryApplication__c where Id=:id];
        InstrumentDeliveryApplication__c ida   = null;
        if(eprpList.size() > 0){
            ida = eprpList[0];
        }else{
            return '仪器发货申请单Id错误!';
        }

        System.debug(ida.IsSycNCBuy__c );
        
        if(ida.IsSycNCBuy__c == true)return 'ok';
       // if(ida.Status__c != '审批成功')return '未审批的工程配件需求计划申请不能同步!';
        if(ida.DemandWarehouse__c == null)return '仪器发货申请单需求仓库必填!';
        if(ida.InventoryStatus__c == null)return '仪器发货申请单出库公司必填!';

        String companyCode= ImportObject.getPicklistValues('Opportunity', 'Corpcode__c', false).get(ida.InventoryStatus__c);
        //if(ida.IsSycToNc__c ==true ) return '已经同步,不要重复点击!';
    
        User u = [select Id, ExuserCode__c from User where Id =:UserInfo.getUserId()];

        Map<String,String> headMap = new Map<String,String>();
        headMap.put('caccountyear',String.valueOf(System.now().year()));

        headMap.put('pk_corp',companyCode);
        headMap.put('coperator',u.ExuserCode__c);

        headMap.put('dpraydate',System.now().format('yyyy-MM-dd'));
        headMap.put('vmemo',ida.Remark__c );

        headMap.put('vdef19',ida.Name  );
        headMap.put('pk_defdoc17', ida.Id );
        //headMap.put('vdef20',eprp.Id );

        // List<InstrumentDeliverynDetails__c> eprdList  = [select Id,DeliveryInstrument__r.Product__r.NCcode__c,Number__c
        // from InstrumentDeliverynDetails__c where ReturnToMainTable__c =: id  ];

        List<NCOutsourcingProducts__c> eprdList  = [select Id,Number__c,OrderMethod__c,NCProducts__r.NCCode__c,InstrumentDeliveryDetails__r.Number__c ,NCProducts__r.Name from NCOutsourcingProducts__c where InstrumentDeliveryDetails__r.ReturnToMainTable__c =: id  ];
      
        if(eprdList.size() == 0)return '没有未同步的配件明细!';
        ///分单
        List<Map<String,String>> bodyList = new List<Map<String,String>>();
        Integer i = 0;
        for (NCOutsourcingProducts__c idd  : eprdList) {

            if(idd.OrderMethod__c == '客户自备' || idd.OrderMethod__c == '不需订购')continue;

            if(idd.InstrumentDeliveryDetails__r.Number__c == null || idd.InstrumentDeliveryDetails__r.Number__c == 0   ) return idd.InstrumentDeliveryDetails__r.Name + ' : 请明确仪器数量!';
            
            if(idd.Number__c ==  null || idd.Number__c == 0 )  return idd.NCProducts__r.Name + ' :请明确仪器数量!';

            if(idd.NCProducts__r.NCCode__c  == null ) return idd.NCProducts__r.Name + ' :请明确发货明细对应的NC产品(确保产品有存货编码)!' ;

            i ++ ;
            Map<String,String> body = new Map<String,String>();
            body.put('rowno', String.valueOf(i));
            body.put( 'cmangid',idd.NCProducts__r.NCCode__c);//存货编码
            body.put('npraynum',String.valueOf(idd.Number__c * idd.InstrumentDeliveryDetails__r.Number__c ));//订货量
            body.put('ddemanddate',System.now().format('yyyy-MM-dd') );
            body.put('pk_corp',companyCode );//公司编码
            body.put('pk_reqcorp',companyCode );//公司编码
            body.put('pk_purcorp',companyCode);//公司编码 
            body.put('cwarehouseid',ida.DemandWarehouse__c );//仓库
            body.put('pk_defdoc17',idd.Id );//仓库

            bodyList.add(body);

        }


        //组装XML 
        String xml = '<ufinterface roottag="bill" billtype="20" replace="Y" receiver="web" sender="20" isexchange="Y"  proc="add" operation="req">';
        xml += '<bill id="'+ida.Id+'" subdoctype="">';
        //组装表头
        xml+='<billhead>';
        for (String k : headMap.keySet()) {
            xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
        }
        xml+='</billhead>';

        //组装表体
        xml+='<billbody>';
        for (Map<String,String> row : bodyList) {
            xml+='<entry>';
            for (String k : row.keySet()) {
                xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
            }
            xml+='</entry>';

        }
        xml+='</billbody>';

        xml +='</bill></ufinterface>';

        System.debug(xml);

        String postURL = Label.queryNCPreOrder;
       //测试环境地址: 
       // postURL = 'https://esb.maccura.com:9088/api/Domain/even1/ncstock/data';
        ///发送请求
        String data = EncodingUtil.urlEncode(xml,'UTF-8');
        //生成POST请求
        HttpRequest req = new HttpRequest(); 
        // String accountn = 'CS180824' ; // 正式'01'
         String accountn = '01' ; // 正式'01' 测试 10

        req.setBody('data=' + data+'&account='+accountn+'&receiver='+companyCode);
        req.setEndpoint(postURL); 
        System.debug(req.getBody());
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** : ' + result);
        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  /*
                {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                  */
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
                List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                    Map<String,Object> rs = (   Map<String,Object>)rList[0];
                    if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                       /* for (SameBatchNumber__c sd: sdList) {
                           
                        }*/
                        String resJso = JSON.serialize(rs);
                        ida.ResultMsg3__c = resJso.length() > 255 ? resJso.substring(0, 254) : resJso;
                        ida.IsSycNCBuy__c = true;
                        update ida;
                        //Approval.lock(sn);
                        return 'ok';
                    }else{
                        return String.valueOf(rs.get('resultdescription'));
                    }


             }else{

                return '同步请购单接口异常,请联系系统管理员!';
             }



        }else{

            return '同步请购单接口异常,请联系系统管理员!';
        }



    }

    public static  Map<String,String > syncOutdoor(List<OutdoorBean> outdoorList){
        Map<String,String > returnMap = new Map<String,String>();
        returnMap.put('code', '1');//失败;

        String url = Label.NCLrckInterface;

            Map<String,Object> data = new Map<String,Object>();
            data.put('data', outdoorList);


            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setBody(JSON.serialize(data) );
            System.debug(JSON.serialize(data));
            req.setHeader('Content-Type','text/plain');
            //req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
            req.setEndpoint(url);
            HttpResponse res = Utils.postRequest(req, 1);
            String sycmsg = '';
             ///返回结果处理
            if (res.getStatusCode() == 200) {
                System.debug(res.getBody());
                Map<String,Object> r = null;
                  //如果是测试
                    if(Test.isRunningTest()){
                        Map<String,Object>  resBody= new Map<String,Object>();
                        resBody.put('code','0');
                        resBody.put('result','{\"result_msg\":\"UPT40088-000001\",\"result\":1}');
                        r =  resBody;
                    }else{
                        r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                    }
              if(r.get('code') == 0 || r.get('code') == '0'){
                    Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                    
                  if( (rs.get('result') == 1 || rs.get('result') == '1' ) ){
                        
                        returnMap.put('code', '0');
                        sycmsg = String.valueOf(r.get('result'));

                   }else{
                        sycmsg = '同步出库单据失败 : '+rs.get('result_msg');
                   }

                }else{

                    sycmsg = '同步出库单据失败 : '+String.valueOf(r.get('msg'));
                }

            }else{
                 sycmsg = '同步出库单据失败 : '+res.getBody();
            }
            returnMap.put('msg', sycmsg);
            return returnMap ;



    }

    public class OutdoorBean{

        //public String approver;//审批人

        public String  cbizid ;

        //public String cdptid;

        public String dbilldate ;
        public String operator;
        public String pk_corp; 

        public String  pk_org_id ;
        public String vnote;
        public String totalnum ;
        public String recvnotes;
        public String isentity; 

        public String  cgphone ;
        public String nextaction;
        public String nextbilltype ;
        public String custcode;
        public String invcode; 

        public String  ts ;
        public String sapply_hid;
        public String sapply_bid ;
        public String applynum;
        public String zdcode;
        public String planrecivedate;//计划领用日期
        public String isInstallsale;//是否分期销售
        public String sfmanid;
        public String sflistid;

        public String pk_defdoc10;
       public String vuserdef10;
        public OutdoorBean() {}
        public OutdoorBean(NCOutsourcingProducts__c np, InstrumentDeliveryApplication__c ida ,String corpcode,String opr ){
            
            //approver = '';
            sfmanid = ida.Id;
            sflistid = np.Id;
            cbizid = ida.Owner.Name;
            //cdptid = ida.Owner.;
            dbilldate = System.now().format('yyyy-MM-dd');
            planrecivedate = System.now().format('yyyy-MM-dd');
            operator =  opr ;
            pk_corp = corpcode;
            //vnote = np.Remarks__c;
            totalnum = '0';
            recvnotes = ida.ReceivingAddress__c ;
            vnote = ida.Remark__c ;
            zdcode = ida.ReceivingCustomer__r.AccountNumber == null ? '' : ida.ReceivingCustomer__r.AccountNumber  ;
            isentity = ida.PhysicalDelivery__c;

            cgphone = ida.ReceiverTelephone__c;
            nextaction = ida.FollowupProcessing__c ;
            nextbilltype =  ida.DocumentTypes__c ;
            custcode = ida.InvoicingCustomers__r.AccountNumber;

            invcode = np.NCProducts__r.NCCode__c;

            ts = System.now().format('yyyy-MM-dd HH:mm:ss');

            sapply_hid = ida.Id;

            sapply_bid = np.Id;
            isInstallsale = '否';

            applynum = String.valueOf(np.Number__c * np.InstrumentDeliveryDetails__r.Number__c);

            pk_defdoc10 = '0001A1100000010658ZQ';
            vuserdef10 = '仪器申请';

        }
       /* public OutdoorBean(InstrumentDeliverynDetails__c np, InstrumentDeliveryApplication__c ida ,String corpcode,String opr ){
            
            //approver = '';
            sfmanid = ida.Id;
            sflistid = np.Id;
            cbizid = ida.Owner.Name;
            //cdptid = ida.Owner.;
            dbilldate = System.now().format('yyyy-MM-dd');
            planrecivedate = System.now().format('yyyy-MM-dd');
            operator =  opr ;
            pk_corp = corpcode;
            totalnum = '0';
            recvnotes = ida.ReceivingAddress__c ;
            //vnote = ida.Remark__c ;
            zdcode = ida.ReceivingCustomer__r.AccountNumber == null ? '' : ida.ReceivingCustomer__r.AccountNumber  ;
            isentity = ida.PhysicalDelivery__c;

            cgphone = ida.ReceiverTelephone__c;
            nextaction = ida.FollowupProcessing__c ;
            nextbilltype =  ida.DocumentTypes__c ;
            custcode = ida.InvoicingCustomers__r.AccountNumber;

            invcode = np.DeliveryInstrument__r.Product__r.NCCode__c;

            ts = System.now().format('yyyy-MM-dd HH:mm:ss');

            sapply_hid = ida.Id;

            sapply_bid = np.Id;
            isInstallsale = '否';

            applynum = String.valueOf(np.Number__c );



        }*/

    }
    
}
/*
sfmanid
sflistid 
approver    否   string  审批人 （工号）

cbizid  否   string  申请人 （名字）

cdptid  否   string  申请人部门（编码）

dbilldate   否   string  单据日期

operator    否   string  制单人 （工号）

pk_corp 否   string  公司 （编码）
pk_org_id   否   string  库存组织 （编码）
vnote   是   string  备注
totalnum    是   string  总数量
recvnotes   否   string  收货信息备注
isentity    否   string  是否实物发货（是/否）
cgphone 否   string  收货人联系方式
nextaction  否   string  后续处理方式
nextbilltype    否   string  下游单据类型
custcode    否   string  客商（ID）
invcode 否   string  存货ID
ts  否   string  时间戳
sapply_hid  否   string  表头ID
sapply_bid  否   string  表体ID
applynum    否   string  申请数量
*/